package com.itheima.demo01;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/7/11 17:26
 */
public class MyThread implements Runnable {
    private static int ticket = 100;

    @Override
    public void run() {
        while (true) {
            if ("窗口一".equals(Thread.currentThread().getName())) {
                boolean b = synchronizedMethod();
                if (b) {
                    break;
                }

            }
            if ("窗口二".equals(Thread.currentThread().getName())) {
                synchronized (MyThread.class) {
                    if (ticket == 0) {
                        break;
                    } else {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticket--;
                        System.out.println(Thread.currentThread().getName() + "正在卖票,还剩余" + ticket + "张票!");
                    }
                }
            }
        }
    }
    private static synchronized boolean synchronizedMethod() {
        if (ticket == 0) {
            return true;
        } else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket--;
            System.out.println(Thread.currentThread().getName() + "正在卖票,还剩余" + ticket + "张票!");
        }
        return false;
    }
}
